package com.ycu.jk16.mall.dao.provider;

import static com.ycu.jk16.mall.util.common.AndroidMalConstant.USERTABLE;

import java.util.Map;

import org.apache.ibatis.jdbc.SQL;

import com.ycu.jk16.mall.domain.User;

/**
 * 
 * @ClassName UserDynaSqlProvider
 * @Description TODO(User表动态查询)
 * @author 倪宗龙
 * @date 2018年12月8日 下午5:05:51
 * @version V1.0
 */
public class UserDynaSqlProvider {
	// 带参数的选择
	public String selectWhitParam(Map<String, Object> params) {
		String sql = new SQL() {
			{
				SELECT("*");
				FROM(USERTABLE);
				if (params.get("user") != null) {
					User user = (User) params.get("user");
					if (user.getId() != null && !user.getId().equals("")) {
						WHERE(" username LIKE CONCAT ('%',#{user.username},'%') ");
					}
				}
			}
		}.toString();

		// 此处加入了分页限制，每页显示 = (页数-1)*每页显示数, 页数*每页显示数 -1
		if (params.get("pageNum") != null) {
			int pageNum = (Integer) params.get("pageNum");
			int pageSize = (Integer) params.get("pageSize");
			sql += " limit " + (pageNum - 1) * pageSize + "," + pageSize;
		}

		return sql;
	}

	// 此处可以是动态查询
	public String countUser(Map<String, Object> params) {
		return new SQL() {
			{
				SELECT("count(*)");
				FROM(USERTABLE);

			}
		}.toString();
	}

	// 动态插入
	public String insertUser(User user) {
		return new SQL() {
			{
				INSERT_INTO(USERTABLE);
				// VALUES("数据库字段", "#{java属性名}");
				if (user.getUsername() != null && !user.getUsername().equals("")) {
					VALUES("username", "#{username}");
				}
				if (user.getUsername() != null && !user.getUsername().equals("")) {
					VALUES("password", "#{password}");
				}
				if (user.getEmail() != null && !user.getEmail().equals("")) {
					VALUES("email", "#{email}");
				}
				if (user.getPhone() != null && !user.getPhone().equals("")) {
					VALUES("phone", "#{phone}");
				}
				if (user.getCreateTime() != null && !user.getCreateTime().equals("")) {
					VALUES("create_time", "#{createTime}");
				}
				if (user.getUpdateTime() != null && !user.getUpdateTime().equals("")) {
					VALUES("update_time", "#{updateTime}");
				}
				if (user.getHeadPortraitUrl() != null && !user.getUpdateTime().equals("")) {
					VALUES("headportrait_url", "#{headPortraitUrl}");
				} else {
					VALUES("headportrait_url", "'" + "defaultHeadPortrait.jpg" + "'");
				}
			}
		}.toString();
	}

	// 动态更新
	public String updateUser(User user) {

		return new SQL() {
			{
				UPDATE(USERTABLE);
				if (user.getId() != null) {
					// SET("数据库字段名", "Java属性名")
					SET(" password = #{password} ");
					SET(" email = #{email} ");
					SET(" phone = #{phone} ");
					SET(" headportrait_url = #{headPortraitUrl} ");
					SET(" update_time = #{updateTime} ");
				}

				WHERE(" id = #{id} ");
			}
		}.toString();
	}
}
